<?php
/**
 * Created by PhpStorm.
 * User: win7
 * Date: 2018/5/15 0015
 * Time: 9:44
 */

namespace Wx\Model;
use Think\Model;

use Think\Controller;

use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;

class SmsModel extends Model
{
    protected $autoCheckFields =false;//设置为虚拟模型

    public function send_message($mobile){
        $u_id = session('u_id');
        //查找是否已经注册
        $user = D('member') -> where("mobile = {$mobile} AND id !=".$u_id) -> find();
        if ($user) {
            $date =array(
              'state' => 404,
              'value' => "手机已注册"
            );
            return($date);
        }else{
            return $this->GetSms($mobile);
        }
        // $this->ajaxReturn($data,"JSON");
    }//end fun send_message()

    //发送短信验证码
    public function GetSms($mobile){
        $code = $this->createSMSCode(6);
        require_once APP_PATH."/Api/aliyun_SMS/vendor/autoload.php";
        Config::load();             //加载区域结点配置

        $accessKeyId = 'LTAIBAnHvxfhn95I';//
        $accessKeySecret = 'MhSK9VMjSkTSW9k6TmcMd7HEWdvn89';
        $templateCode = 'SMS_115250181';   //短信模板ID

        //短信API产品名（短信产品名固定，无需修改）
        $product = "Dysmsapi";

        //短信API产品域名（接口地址固定，无需修改）
        $domain = "dysmsapi.aliyuncs.com";

        //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
        $region = "cn-hangzhou";

        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);

        // 增加服务结点
        DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);

        // 初始化AcsClient用于发起请求
        $acsClient = new DefaultAcsClient($profile);

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        // 必填，设置短信接收号码
        $request->setPhoneNumbers($mobile);

        // 必填，设置签名名称
        $request->setSignName("乡土味士");

        // 必填，设置模板CODE
        $request->setTemplateCode($templateCode);

        $smsData = array('code'=>$code);    //所使用的模板若有变量 在这里填入变量的值  我的变量名为username此处也为username

        //选填-假如模板中存在变量需要替换则为必填(JSON格式),友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        $request->setTemplateParam(json_encode($smsData));

        //发起访问请求
        $acsResponse = $acsClient -> getAcsResponse($request);
        //返回请求结果
        $result = json_decode(json_encode($acsResponse), true);
        $resp = $result['Code'];
        return $this->sendMsgResult($resp,$mobile,$code);
    }//end fun GetSms()

    //生成短信验证码 $length [验证码长度]
    public function createSMSCode($length = 6){
        $min = pow(10 , ($length - 1));
        $max = pow(10, $length) - 1;
        return rand($min, $max);
    }//end fun

    private function sendMsgResult($resp,$mobile,$code){
        if ($resp == "OK") {
            $date = array(
                'state' => 0,
                'mobile' => $mobile,
                'code' => $code,
                'value' => '发送成功',
                'send_time' => time()
            );
        }else{
            $date = array(
                'state' => 404,
                'value' => '发送失败',
            );
        }
        return($date);
    }//end fun
}//end class